import React from 'react';
import {Modal, Form, Input, Select, Checkbox, Radio, Button, Table, message} from 'antd';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
import {WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

import FormGroup from './base/FormGroup';

import {WeaBrowser, WeaLocaleProvider} from 'ecCom';

// 外部数据元素，数据来源
class Content_OutData_DataSource extends React.Component {
    state = {
        id: this.props.tabData.id,
        title: this.props.tabData.title,
        sourceType: this.props.tabData.sourceType || this.props.tabNew.sourceType,
        dataSourceList: this.props.tabData.dataSourceList || [],
        dataSourceType: this.props.tabData.dataSourceType || this.props.tabNew.dataSourceType.selected,
        dataSource: this.props.tabData.dataSource || this.props.tabNew.dataSource.selected,
        content: this.props.tabData.content,
        primaryKey: this.props.tabData.primaryKey,
        linkAddress: this.props.tabData.linkAddress,
        integrateLogin: this.props.tabData.integrateLogin || this.props.tabNew.integrateLogin.selected,
        showFieldSetting: this.props.tabData.showFieldSetting || [],
        dsModalVisible: true
    };

    onOk(e) {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                return;
            }

            this.props.onOk(values);
        });
    }

    onCancel() {
        this.props.onCancel();
    }

    onShowFieldChange(key, type, e) {
        let showFieldSetting = this.state.showFieldSetting;

        if (type == 'isTitle') {
            for (let i = 0, len = showFieldSetting.length; i < len; i++) {
                showFieldSetting[i]['isTitle'] = false;
            }
            showFieldSetting[key]['isTitle'] = e.target.checked;
        } else {
            showFieldSetting[key][type] = e.target.value;
        }

        this.setState({
            showFieldSetting: showFieldSetting
        });
    }

    onSourceTypeChange(e) {
        this.setState({
            sourceType: e.target.value
        });
    }

    onDelete() {
        let showFieldSetting = this.state.showFieldSetting;

        if (this.selectedRowKeys && this.selectedRowKeys.length) {
            const selectedRowKeys = this.selectedRowKeys.slice();
            for (let i = 0, len = selectedRowKeys.length; i < len; i++) {
                this.selectedRowKeys.splice(i, 1);

                for (let j = 0, len2 = showFieldSetting.length; j < len2; j++) {
                    if (showFieldSetting[j].key == selectedRowKeys[i]) {
                        showFieldSetting.splice(j, 1);
                        break;
                    }
                }
            }
        } else {
            message.warn('请选择需要删除的行！', 3);
        }

        this.setState({
            showFieldSetting: showFieldSetting
        });
    }

    onAdd() {
        let showFieldSetting = this.state.showFieldSetting;
        let key = showFieldSetting.length;

        showFieldSetting.push({
            "key": key,
            "showName": "",
            "showField": "",
            "isTitle": false,
            "transformMethod": ""
        });

        this.setState({
            showFieldSetting: showFieldSetting
        });
    }

    onDataSourceChange(sourceId, sourceName) {
        const dataSourceList = [];

        if (!!sourceId) {
            dataSourceList.push({
                "key": sourceId,
                "sourceId": sourceId,
                "sourceName": sourceName,
                "integrateLogin": ""
            });
        }

        this.setState({
            dataSourceList: dataSourceList
        });
    }

    onIntegrateLoginChange(sourceId, value) {
        let dataSourceList = this.state.dataSourceList;

        for (let i = 0, len = dataSourceList.length; i < len; i++) {
            if (dataSourceList[i].sourceId == sourceId) {
                dataSourceList[i].integrateLogin = value;
                break;
            }
        }

        this.setState({
            dataSourceList: dataSourceList
        });
    }

    render() {
        const {getFieldProps} = this.props.form;
        const formItemLayout = this.props.formItemLayout;
        const tabNew = this.props.tabNew;

        getFieldProps('id', {initialValue: this.state.id});

        const titleProps = getFieldProps('title', {
            initialValue: this.state.title,
            rules: [
                {required: true, message: getLabel(388007,"请填写标题")},
            ]
        });

        const sourceTypeProps = getFieldProps('sourceType', {initialValue: this.state.sourceType});

        let existSetting = <div></div>;
        let customSetting = <div></div>;
        let customSettingGroup = <div></div>;
        if (this.state.sourceType == '1') {
            getFieldProps('dataSourceList', {initialValue: this.state.dataSourceList});

            const integrateLoginOptions = tabNew.integrateLogin.options.map((item, index) => {
                return <Option key={index} value={item.key}>{item.value}</Option>;
            });

            // 表格列
            const columns = [{
                title: getLabel(30231,"数据来源名称"),
                dataIndex: 'sourceName',
                width: '30%',
                render: (text, record) => (
                    <span>{record.sourceName}</span>
                )
            }, {
                title: getLabel(125405,"集成登录设置"),
                key: 'integrateLogin',
                width: '70%',
                render: (text, record) => (
                    <Select size="default" style={{width: '80%'}} value={record.integrateLogin} onChange={this.onIntegrateLoginChange.bind(this, record.sourceId)}>
                        {integrateLoginOptions}
                    </Select>
                )
            }];

            const dataSource = this.state.dataSourceList;

            let opsDatas = [];
            for (let i = 0, len = dataSource.length; i < len; i++) {
                opsDatas.push({
                    id: dataSource[i].sourceId,
                    name: dataSource[i].sourceName
                });
            }

            existSetting = (
                <div>
                    <div style={{width: '80%', margin: '8px 0'}}>
                        <WeaBrowser selectSize="default" resize={true} type="exterbaldata" opsDatas={opsDatas} onChange={this.onDataSourceChange.bind(this)}/>
                    </div>
                    <Table className="esetting-table" columns={columns} dataSource={dataSource} pagination={false}/>
                </div>
            );
        } else if (this.state.sourceType == '2') {
            const dataSourceTypeProps = getFieldProps('dataSourceType', {initialValue: this.state.dataSourceType});
            const dataSourceTypeOptions = tabNew.dataSourceType.options.map((item, index) => {
                return <Option key={index} value={item.key}>{item.value}</Option>;
            });

            const dataSourceProps = getFieldProps('dataSource', {initialValue: this.state.dataSource});
            const dataSourceOptions = tabNew.dataSource.options.map((item, index) => {
                return <Option key={index} value={item.key}>{item.value}</Option>;
            });

            const contentProps = getFieldProps('content', {initialValue: this.state.content});

            const primaryKeyProps = getFieldProps('primaryKey', {initialValue: this.state.primaryKey});

            const linkAddressProps = getFieldProps('linkAddress', {initialValue: this.state.linkAddress});

            const integrateLoginProps = getFieldProps('integrateLogin', {initialValue: this.state.integrateLogin});
            const integrateLoginOptions = tabNew.integrateLogin.options.map((item, index) => {
                return <Option key={index} value={item.key}>{item.value}</Option>;
            });

            const sItemStyle = {
                margin: '8px 0'
            };
            customSetting = (
                <div>
                    <div style={sItemStyle}>
                        <span style={{display: 'inline-block', width: '80px'}}>{getLabel(28006,"数据来源")}</span>
                        <Select size="default" style={{width: '120px'}} {...dataSourceTypeProps}>
                            {dataSourceTypeOptions}
                        </Select>
                    </div>
                    <div style={sItemStyle}>
                        <span style={{display: 'inline-block', width: '80px'}}>{getLabel(18076,"数据源")}</span>
                        <Select size="default" style={{width: '120px'}} {...dataSourceProps}>
                            {dataSourceOptions}
                        </Select>
                    </div>
                    <div style={sItemStyle}>
                        <span style={{display: 'inline-block', width: '80px', verticalAlign: 'top'}}>{getLabel(33368,"内容")}</span>
                        <Input type="textarea" size="default" rows={4} style={{width: '360px'}} {...contentProps}/>
                    </div>
                    <div style={sItemStyle}>
                        <span style={{display: 'inline-block', width: '80px'}}>{getLabel(21027,"主键")}</span>
                        <Input type="text" size="default" style={{width: '360px'}} {...primaryKeyProps}/>
                    </div>
                    <div style={sItemStyle}>
                        <span style={{display: 'inline-block', width: '80px'}}>{getLabel(16208,"链接地址")}</span>
                        <Input type="text" size="default" style={{width: '360px'}} {...linkAddressProps}/>
                    </div>
                    <div style={sItemStyle}>
                        <span style={{display: 'inline-block', width: '80px'}}>{getLabel(125405,"集成登录设置")}</span>
                        <Select size="default" style={{width: '360px'}} {...integrateLoginProps}>
                            {integrateLoginOptions}
                        </Select>
                    </div>
                </div>
            );

            const dataSource = this.state.showFieldSetting;
            getFieldProps('showFieldSetting', {initialValue: dataSource});

            // 记录选中的tab数据行
            const _self = this;
            const rowSelection = {
                onChange(selectedRowKeys) {
                    _self.selectedRowKeys = selectedRowKeys;
                }
            };

            // 表格列
            const columns = [{
                title:getLabel(15456, '字段显示名'),
                dataIndex: 'showName',
                render: (text, record) => (
                    <Input type="text" size="default" style={{width: '90%'}} defaultValue={record.showName} onChange={this.onShowFieldChange.bind(this, record.key, 'showName')}/>
                )
            }, {
                title: getLabel(32320,"显示字段/XML路径"),
                key: 'showField',
                render: (text, record) => (
                    <Input type="text" size="default" style={{width: '90%'}} defaultValue={record.showField} onChange={this.onShowFieldChange.bind(this, record.key, 'showField')}/>
                )
            }, {
                title:getLabel(22965, '标题栏'),
                key: 'isTitle',
                render: (text, record) => (
                    <Checkbox size="default" checked={record.isTitle} onChange={this.onShowFieldChange.bind(this, record.key, 'isTitle')}/>
                )
            }, {
                title: getLabel(32321,"转换方法"),
                key: 'transformMethod',
                render: (text, record) => (
                    <Input type="textarea" size="default" rows={1} style={{width: '90%'}} defaultValue={record.transformMethod} onChange={this.onShowFieldChange.bind(this, record.key, 'transformMethod')}/>
                )
            }];

            const formGroupButtons = (
                <div className="esetting-dso">
                    <div className="esetting-dso-add" title={getLabel(611, '添加')} onClick={this.onAdd.bind(this)}></div>
                    <div className="esetting-dso-deletes" title={getLabel(91, '删除')} onClick={this.onDelete.bind(this)}></div>
                </div>
            );

            customSettingGroup = (
                <FormGroup title={getLabel(32317, "显示字段设置")} buttons={formGroupButtons}>
                    <Table className="esetting-table" rowSelection={rowSelection} columns={columns} dataSource={dataSource} pagination={false}/>
                </FormGroup>
            );
        }

        return (
            <Modal
                title={getLabel(19480, '内容设置') }
                width="660px"
                wrapClassName="esetting-modal"
                visible={this.state.dsModalVisible}
                footer={
                    <div className="esetting-confirm">
                        <Button type="primary" onClick={this.onOk.bind(this)}>{getLabel(826, '确定')}</Button>
                        <span>&nbsp;&nbsp;&nbsp;</span>
                        <Button type="ghost" onClick={this.onCancel.bind(this)}>{getLabel(31129, '取消')}</Button>
                    </div>
                }
                onOk={this.onOk.bind(this)}
                onCancel={this.onCancel.bind(this)}
            >
                <Form horizontal className="esetting-form">
                    <FormGroup title={getLabel(33396,"设置项")}>
                        <FormItem label={getLabel(24986, '标题')} {...formItemLayout}>
                            <Input type="text" size="default" style={{width: '467px'}} {...titleProps}/>
                        </FormItem>
                        <FormItem label={getLabel(28006,"数据来源")} {...formItemLayout}>
                            <RadioGroup style={{width: '100%'}} {...sourceTypeProps} onChange={this.onSourceTypeChange.bind(this)}>
                                <Radio value="1">{getLabel(81511,"已有数据集成")}</Radio>
                                <Radio value="2">{getLabel(32219,"自定义方式")}</Radio>
                            </RadioGroup>
                            {existSetting}
                            {customSetting}
                        </FormItem>
                    </FormGroup>
                    {customSettingGroup}
                </Form>
            </Modal>
        );
    }
}

Content_OutData_DataSource = Form.create()(Content_OutData_DataSource);

export default Content_OutData_DataSource;